/**
 * 设置页面title
 * v-set-title="string"
 */
const setTitle = (el, binding) => {
  const title = binding.value
  const mobile = navigator.userAgent.toLowerCase()

  if (title === undefined || window.document.title === title) {
    return
  }
  document.title = title

  if (/iphone|ipad|ipod/.test(mobile)) {
    const iframe = document.createElement('iframe')
    iframe.style.display = 'none'

    const iframeCallback = () => {
      setTimeout(() => {
        iframe.removeEventListener('load', iframeCallback)
        document.body.removeChild(iframe)
      }, 0)
    }
    iframe.addEventListener('load', iframeCallback)
    document.body.appendChild(iframe)
  }
}

/**
 * 设置页面meta,配置name、content
 * v-set-meta:keywords="$route.meta.keywords"
 */
const setMeta = (el, binding) => {
  const metaName = binding.arg
  const metaContent = binding.value
  let isHas = false
  const meta = document.getElementsByTagName('meta')

  if (metaName === undefined || metaContent === undefined) {
    return
  }
  for (const i in meta) {
    if (meta[i].name === metaName) {
      meta[i].content = metaContent
      isHas = true
      return
    }
  }
  if (!isHas) {
    const head = document.getElementsByTagName('head')
    const newMeta = document.createElement('meta')
    newMeta.name = metaName
    newMeta.content = metaContent
    head[0].appendChild(newMeta)
  }
}

export const setupSetTitleDirective = (app) => {
  app.directive('set-title', setTitle)
}
export const setupSetMetaDirective = (app) => {
  app.directive('set-meta', setMeta)
}
